#include "roomhandler.hpp"
#include "roomblueprint.hpp"
#include "resourcehandler.hpp"
#include "exception.hpp"
#include <algorithm>

namespace nmc
{
	RoomHandler *RoomHandler::mInstance = 0;

	RoomHandler::RoomHandler()
	{
	}

	void RoomHandler::destroy()
	{
		std::map<std::string, RoomBlueprint*>::iterator iter;
		
		for (iter = mRoomBlueprints.begin(); iter != mRoomBlueprints.end(); iter++)
		{
			delete iter->second;
		}

		mRoomBlueprints.clear();
	}

	RoomHandler *RoomHandler::getInstance()
	{
		if (mInstance == 0)
		{
			mInstance = new RoomHandler();
		}

		return mInstance;
	}

	void RoomHandler::saveRoomBlueprint(const std::string& filename)
	{
		if (mRoomBlueprints.find(filename) == mRoomBlueprints.end())
		{
			throw NMC_EXCEPTION("Unable to save non loaded room blueprint for file " + filename);
		}

		std::string realFilename = ResourceHandler::getInstance()->getRealFilename("rooms/"+filename);
		mRoomBlueprints[filename]->save(realFilename);
	}
	
	RoomBlueprint *RoomHandler::getRoomBlueprint(const std::string& filename)
	{
		if (mRoomBlueprints.find(filename) == mRoomBlueprints.end())
		{
			std::string realFilename = ResourceHandler::getInstance()->getRealFilename("rooms/"+filename);
			mRoomBlueprints[filename] = new RoomBlueprint(realFilename);
		}

		return mRoomBlueprints[filename];
	}

	std::vector<std::string> RoomHandler::getAvailableRooms()
	{
		struct al_ffblk info;
        std::string pattern = ResourceHandler::getInstance()->getRealFilename("rooms/*.rb");

		std::vector<std::string> rooms;

		if (al_findfirst(pattern.c_str(), &info, FA_ALL)) 
		{
			al_findclose(&info);
			return rooms;
		}

        do
        {
            std::string foundName = std::string(info.name);
  
            // Remove trailing .rb from name.
            //foundName = foundName.substr(0, foundName.length() - 3);
			
			rooms.push_back(foundName);

        } while (al_findnext(&info) == 0);
       
        al_findclose(&info);

		std::sort(rooms.begin(), rooms.end());

		return rooms;
	}
}
